<template>
  <a-modal :open="visible" title="编辑个人资料" width="800px" :confirm-loading="loading" @ok="handleSubmit" @cancel="handleCancel" :maskClosable="false">
    <a-form ref="formRef" :model="formData" :rules="rules" layout="vertical" class="profile-form">
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="用户名" name="username">
            <a-input v-model:value="formData.username" placeholder="请输入用户名" :maxlength="20" />
          </a-form-item>
        </a-col>

        <a-col :span="12">
          <a-form-item label="头像" name="avatar">
            <div class="avatar-upload">
              <a-avatar :size="64" :src="formData.avatar" class="avatar-preview" :style="{ backgroundColor: formData.avatar ? 'transparent' : '#1890ff' }">
                {{ formData.username?.charAt(0)?.toUpperCase() || 'U' }}
              </a-avatar>
              <a-input v-model:value="formData.avatar" placeholder="请输入头像URL" class="avatar-input" />
            </div>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="开始工作日期" name="work_start_date">
            <a-date-picker v-model:value="workStartDate" placeholder="选择开始工作日期" style="width: 100%" :disabledDate="disabledDate" />
          </a-form-item>
        </a-col>

        <a-col :span="12">
          <a-form-item label="职业方向" name="career_direction">
            <a-select v-model:value="formData.career_direction" placeholder="请选择职业方向" :options="careerOptions" allowClear />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="职位" name="position">
            <a-input v-model:value="formData.position" placeholder="请输入职位" :maxlength="50" />
          </a-form-item>
        </a-col>

        <a-col :span="12">
          <a-form-item label="公司" name="company">
            <a-input v-model:value="formData.company" placeholder="请输入公司名称" :maxlength="100" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item label="个人介绍" name="bio">
        <a-textarea v-model:value="formData.bio" placeholder="简单介绍一下自己..." :rows="4" :maxlength="500" show-count />
      </a-form-item>

      <a-form-item label="兴趣标签" name="interest_tags">
        <div class="interest-tags">
          <a-tag v-for="(tag, index) in formData.interest_tags" :key="index" closable @close="removeTag(index)" class="tag-item">
            {{ tag }}
          </a-tag>

          <a-input v-if="tagInputVisible" ref="tagInputRef" v-model:value="tagInputValue" @blur="handleTagInputConfirm" @keyup.enter="handleTagInputConfirm" placeholder="输入标签" class="tag-input" />

          <a-tag v-else @click="showTagInput" class="add-tag"> <plus-outlined /> 添加标签 </a-tag>
        </div>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import { ref, watch, nextTick, computed } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { getToken } from '@/utils/auth'
import dayjs from 'dayjs'
import { API_BASE_URL } from '@/utils/api'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  profileData: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:visible', 'success'])

const formRef = ref()
const loading = ref(false)
const tagInputVisible = ref(false)
const tagInputRef = ref()
const tagInputValue = ref('')

// 表单数据
const formData = ref({
  username: '',
  avatar: '',
  work_start_date: '',
  career_direction: '',
  position: '',
  company: '',
  bio: '',
  interest_tags: []
})

// 工作开始日期处理
const workStartDate = computed({
  get: () => {
    return formData.value.work_start_date ? dayjs(formData.value.work_start_date) : null
  },
  set: (val) => {
    formData.value.work_start_date = val ? val.format('YYYY-MM-DD') : ''
  }
})

// 禁用未来日期
const disabledDate = (current) => {
  return current && current > dayjs().endOf('day')
}

// 职业方向选项
const careerOptions = [
  { label: '前端开发', value: '前端开发' },
  { label: '后端开发', value: '后端开发' },
  { label: '全栈开发', value: '全栈开发' },
  { label: '移动端开发', value: '移动端开发' },
  { label: 'UI/UX设计', value: 'UI/UX设计' },
  { label: '产品经理', value: '产品经理' },
  { label: '测试工程师', value: '测试工程师' },
  { label: '运维工程师', value: '运维工程师' },
  { label: '数据分析师', value: '数据分析师' },
  { label: '算法工程师', value: '算法工程师' },
  { label: '架构师', value: '架构师' },
  { label: '技术管理', value: '技术管理' },
  { label: '其他', value: '其他' }
]

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  position: [{ max: 50, message: '职位长度不能超过50个字符', trigger: 'blur' }],
  company: [{ max: 100, message: '公司名称长度不能超过100个字符', trigger: 'blur' }],
  bio: [{ max: 500, message: '个人介绍长度不能超过500个字符', trigger: 'blur' }]
}

// 监听 visible 变化，初始化表单数据
watch(
  () => props.visible,
  (newVal) => {
    if (newVal && props.profileData) {
      formData.value = {
        username: props.profileData.username || '',
        avatar: props.profileData.avatar || '',
        work_start_date: props.profileData.work_start_date || '',
        career_direction: props.profileData.career_direction || '',
        position: props.profileData.position || '',
        company: props.profileData.company || '',
        bio: props.profileData.bio || '',
        interest_tags: [...(props.profileData.interest_tags || [])]
      }
    }
  },
  { immediate: true }
)

// 处理提交
const handleSubmit = async () => {
  try {
    await formRef.value.validate()

    loading.value = true

    const response = await fetch(`${API_BASE_URL}/auth/profile`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${getToken()}`
      },
      body: JSON.stringify(formData.value)
    })

    const result = await response.json()

    if (result.code === 200) {
      emit('success')
      emit('update:visible', false)
    } else {
      message.error(result.msg || '更新失败')
    }
  } catch (error) {
    console.error('更新个人资料失败:', error)
    message.error('更新失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 处理取消
const handleCancel = () => {
  emit('update:visible', false)
}

// 显示标签输入框
const showTagInput = () => {
  tagInputVisible.value = true
  nextTick(() => {
    tagInputRef.value?.focus()
  })
}

// 确认添加标签
const handleTagInputConfirm = () => {
  const inputValue = tagInputValue.value.trim()

  if (inputValue && !formData.value.interest_tags.includes(inputValue)) {
    if (formData.value.interest_tags.length >= 10) {
      message.warning('最多只能添加10个标签')
    } else {
      formData.value.interest_tags.push(inputValue)
    }
  }

  tagInputVisible.value = false
  tagInputValue.value = ''
}

// 移除标签
const removeTag = (index) => {
  formData.value.interest_tags.splice(index, 1)
}
</script>

<style scoped>
.profile-form {
  max-height: 600px;
  overflow-y: auto;
}

.avatar-upload {
  display: flex;
  align-items: center;
  gap: 12px;
}

.avatar-preview {
  flex-shrink: 0;
  background-color: #1890ff;
}

.avatar-input {
  flex: 1;
}

.interest-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.tag-item {
  margin: 0;
  user-select: none;
}

.tag-input {
  width: 120px;
}

.add-tag {
  cursor: pointer;
  border-style: dashed;
  background: #fafafa;
  border-color: #d9d9d9;
  color: #666;
  margin: 0;
}

.add-tag:hover {
  border-color: #1890ff;
  color: #1890ff;
}

:deep(.ant-form-item-label) {
  font-weight: 600;
}

:deep(.ant-input:focus),
:deep(.ant-input-focused) {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

:deep(.ant-select:focus),
:deep(.ant-select-focused) .ant-select-selector {
  border-color: #1890ff !important;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2) !important;
}
</style>
